import os
import json
import time
from threading import Lock

class FileCache:
    """
    基于文件的缓存实现
    支持设置过期时间、并发安全的读写操作
    """
    
    def __init__(self, cache_dir='__cache'):
        """
        初始化缓存
        :param cache_dir: 缓存目录
        """
        self.cache_dir = cache_dir
        self.lock = Lock()
        
        # 确保缓存目录存在
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)
    
    def _get_cache_path(self, key):
        """获取缓存文件路径"""
        return os.path.join(self.cache_dir, f"{key}.cache")
    
    def set(self, key, value, timeout=None):
        """
        设置缓存
        :param key: 缓存键
        :param value: 缓存值
        :param timeout: 过期时间(秒)
        """
        cache_data = {
            'value': value,
            'expire_time': time.time() + timeout if timeout else None
        }
        
        with self.lock:
            try:
                cache_path = self._get_cache_path(key)
                with open(cache_path, 'w', encoding='utf-8') as f:
                    json.dump(cache_data, f)
                return True
            except Exception as e:
                print(f"设置缓存失败: {str(e)}")
                return False
    
    def get(self, key):
        """
        获取缓存
        :param key: 缓存键
        :return: 缓存值，如果不存在或已过期返回None
        """
        cache_path = self._get_cache_path(key)
        
        if not os.path.exists(cache_path):
            return None
            
        with self.lock:
            try:
                with open(cache_path, 'r', encoding='utf-8') as f:
                    cache_data = json.load(f)
                    
                # 检查是否过期
                if cache_data['expire_time'] and time.time() > cache_data['expire_time']:
                    self.delete(key)
                    return None
                    
                return cache_data['value']
            except Exception as e:
                print(f"获取缓存失败: {str(e)}")
                return None
    
    def delete(self, key):
        """
        删除缓存
        :param key: 缓存键
        """
        cache_path = self._get_cache_path(key)
        
        with self.lock:
            try:
                if os.path.exists(cache_path):
                    os.remove(cache_path)
                return True
            except Exception as e:
                print(f"删除缓存失败: {str(e)}")
                return False
    
    def clear(self):
        """清空所有缓存"""
        with self.lock:
            try:
                for filename in os.listdir(self.cache_dir):
                    if filename.endswith('.cache'):
                        os.remove(os.path.join(self.cache_dir, filename))
                return True
            except Exception as e:
                print(f"清空缓存失败: {str(e)}")
                return False

# 创建默认缓存实例
cache = FileCache()